<template>
  <div ref="wrapper_hook" class="wrapper" />
</template>

<script>
import * as echarts from 'echarts'
export default {
  name: 'line3',
  props: {
    source: {
      type: Object,
      default: () => {
        return {
          xAxis:[],
          series:[]
        }
      }
    },
    yName:{
      type:String,
      default:'台'
    }
  },
  data () {
    return {
      chart: null
    }
  },
  watch: {
    source (newValue) {
      this._initECharts(newValue)
    }
  },
  mounted () {
    this.$nextTick(() => {
      this._initECharts(this.sourceData)
      window.addEventListener('resize', this.resize)
    })
  },
  destroyed () {
    window.removeEventListener('resize', this.resize)
  },
  methods: {
    _initECharts (data) {
      if (!data || data.length === 0) return
      this.chart ? this.update(data) : this.draw(data)
    },
    formatterTool(params) {
      let result = ''
      params.forEach(item => {
        result += `${item.marker} ${item.seriesName}：${item.data}<br />`
      })
      return result
    },
    draw (data) {
      const { xAxis, series } = data
      this.chart = echarts.init(this.$refs.wrapper_hook)
      const options = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: params => this.formatterTool(params)
        },
        grid: {
          left: '2%',
          top: '14%',
          right: 0,
          bottom: '0',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: xAxis,
          axisTick: {
            show: false,
            alignWithLabel: false
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#C7C7C7FF'
            }
          },
          axisLabel: {
            alignWithLabel: true,
            color: '#5a5a5a',
            size: 14,
            // interval: 1,
            // padding: [20, 0, 0, 0],
            align: 'center'
          },
          splitLine: false
        },
        yAxis: [
          {
            // name: this.yName,
            padding:[0,0,0,10],
            type: 'value',
            axisLine: {
              show: true,
              lineStyle: {
                color: '#b4b4b4'
              }
            }
          }
        ],
        series: series
      }
      this.chart.setOption(options)
      this.chart.on('click',params => {
        this.$emit('change',params)
      })
    },
    update (data) {
      if (!this.chart) return
      const { xAxis, series } = data
      const options = this.chart.getOption()
      options.xAxis[0].data = xAxis
      options.series = series
      this.chart.setOption(options, true)
    },
    resize (delay = 400) {
      setTimeout(() => {
        this.chart && this.chart.resize()
      }, delay)
    }
  }
}
</script>

<style  scoped>
  .wrapper {
    width: 100%;
    height:270px;
  }
</style>
